package com.sky.happygos.network;

import com.sky.happygos.common.Constants;
import com.sky.happygos.network.ApiService;

import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.sharedpreferences.Pref;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Jin on 2017/4/13.
 */
@EBean(scope = EBean.Scope.Singleton)
public class Api {


    private static final int DEFAULT_TIMEOUT = 10;//超时时长，单位：秒
    public ApiService service;
    public ApiServiceAuth authService;

    @Pref
    TokenPrefs_ tokenPrefs;

    public ApiService getService(){
        if(service == null) {
            Retrofit retrofit = initRetrofit(false);
            service = retrofit.create(ApiService.class);
        }
        return service;
    }
    public ApiServiceAuth getAuthService(){

        if (authService == null) {
            Retrofit retrofit = initRetrofit(true);
            authService = retrofit.create(ApiServiceAuth.class);
        }
        return authService;
    }



    public Retrofit initRetrofit(boolean auth){
        return new Retrofit.Builder()
                .client(initOkhttp(auth))
                .baseUrl(Constants.IP)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public OkHttpClient initOkhttp(final boolean auth) {

            return  new OkHttpClient.Builder()
                        .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                        .addInterceptor(new HttpLoggingInterceptor())
                        .addInterceptor(new Interceptor() {
                            @Override
                            public Response intercept(Chain chain) throws IOException {
                                Request request = chain.request();
                                if(auth) {
                                    if (tokenPrefs != null) {
                                        String token = tokenPrefs.token().get();
                                        request = request.newBuilder()
                                                .header("key", token)
                                                .build();
                                    }
                                }
                                return chain.proceed(request);
                            }
                        }).build();
    }


}
